package org.example.customs.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.example.commons.common.Result;
import com.example.commons.entity.Category;
import com.example.commons.entity.Collect;
import com.example.commons.entity.Teach;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.example.customs.service.CategoryService;
import org.example.customs.service.CollectService;
import org.example.customs.service.TeachService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

/**
 * @program: authority-v3.0.7
 * @ClassName:TeachController
 * @description: TeachController前端控制器
 * @author:dyy
 * @Version 3.0
 **/

@Tag(name = "回目攻略 前端控制器")
@RestController
@RequestMapping("/teach")
public class TeachController {
    @Resource
    private TeachService teachService;

    @Resource
    private CategoryService categoryService;

    @Resource
    private CollectService collectService;


    /**
     * 新增
     *
     * @param teach
     * @return
     */
    @Operation(summary = "新增")
    @PostMapping
    public Result save(@RequestBody Teach teach) {
        return Result.success(teachService.save(teach));
    }


    /**
     * 修改
     *
     * @param id
     * @param teach
     * @return
     */
    @Operation(summary = "修改")
    @PutMapping("/{id}")
    public Result update(@PathVariable Long id, @RequestBody Teach teach) {
        return Result.success(teachService.updateById(teach));
    }


    /**
     * 查询所有Teach
     *
     * @return
     */
    @Operation(summary = "查询所有Teach")
    @GetMapping
    public Result findAll() {
        return Result.success(teachService.list());
    }


    /**
     * 获取单个
     *
     * @param id
     * @return
     */
    @Operation(summary = "获取单个")
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        Teach teach = teachService.getById(id);
        teach.setIsCollect(collectService.list(
                new LambdaQueryWrapper<Collect>().eq(Collect::getUid, StpUtil.getLoginIdAsLong())
                        .eq(Collect::getAid, id)
        ).size() > 0);
        return Result.success(teach);
    }


    /**
     * 分页显示
     *
     * @param name
     * @param cid
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Operation(summary = "分页显示")
    @GetMapping("/page")
    public Result findPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam(defaultValue = "") Long cid,
                           @RequestParam(defaultValue = "1") Integer pageNum,
                           @RequestParam(defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<Teach> queryWrapper = new LambdaQueryWrapper();
        if (StrUtil.isNotEmpty(name)) {
            // name 不为空且不是空字符串的处理逻辑
            queryWrapper.like(Teach::getName, name);
        }
        if (cid != null && cid != 0) {
            // name 不为空且不是空字符串的处理逻辑
            queryWrapper.eq(Teach::getCid, cid);
        }

        queryWrapper.orderByDesc(Teach::getId);
        Page<Teach> page = teachService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<Teach> records = page.getRecords();
        for (Teach teach : records) {
            Category category = categoryService.getById(teach.getCid());
            if (ObjectUtil.isNotEmpty(category)) {
                teach.setCategory(category);
            }
        }
        page.setRecords(records);
        return Result.success(page);
    }


    /**
     * 单个删除
     *
     * @param id
     * @return
     */
    @Operation(summary = "单个删除")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        collectService.remove(new LambdaQueryWrapper<Collect>()
                .eq(Collect::getAid, id)
        );
        return Result.success(teachService.removeById(id));
    }


    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @Operation(summary = "批量删除")
    @DeleteMapping("/batch/{ids}")
    @Transactional
    public Result deleteByIds(@PathVariable String[] ids) {
        for (String id : ids){
            collectService.remove(new LambdaQueryWrapper<Collect>()
                    .eq(Collect::getAid, id)
            );
        }
        return Result.success(teachService.removeByIds(Arrays.asList(ids)));
    }


    /**
     * 批量导出
     * 使用的技术为alibaba下面的easyexcel
     * 写数据
     *
     * @param ids
     * @return
     */
    @Operation(summary = "批量导出")
    @GetMapping("/batch/export/{ids}")
    public void exportByIds(@PathVariable String[] ids, HttpServletResponse response) throws IOException {
        List<Teach> list = teachService.listByIds(Arrays.asList(ids));

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");

        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("teach导出数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Teach.class).sheet("sheel1").doWrite(list);

    }


    /**
     * 批量导入
     * 使用的技术为alibaba下面的easyexcel
     * 读数据
     *
     * @param
     */
    @Operation(summary = "批量导入")
    @PostMapping("/batch/upload")
    public Result writeExcel(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), Teach.class, new PageReadListener<Teach>(dataList -> {
            dataList.forEach(entity -> teachService.save(entity.toBuilder().id(null).build()));
        })).sheet().doRead();
        return Result.success();
    }
}